import axios from 'axios'
import qs from 'qs'

import API from '../configs/Config'
import { Storage, gotoLogin } from './index'
import store from '../index'

// 全局的 token
global.userToken = ''

// 跳转到登陆页
const navigateLogin = () => {
  const routerState = store.getState()['router']
  const { routes } = routerState
  if (!(routes && routes.length && routes[routes.length - 1].routeName === 'Login')) {
    store.dispatch(gotoLogin)
  }
}

/**
 * @author: chentao
 * @param { string } method - request method to be used when making the request
 * @param { url } url - server URL that will be used for the request
 * @param { object } data - data to be sent as the request body
 */
export async function request({
  method = 'GET',
  url,
  data,
}) {
  try {
    console.log('netUtils')
    const defaultHeaders = { 'Content-Type': 'application/json' }
    defaultHeaders['pl'] = 'app';
    defaultHeaders['mm'] = '';
    defaultHeaders['av'] = '';
    defaultHeaders['sv'] = '';
    defaultHeaders['uuid'] = '';
    console.log('a')
    if (!global.userToken && global.userToken !== null) {
      global.userToken = null
      const user = await Storage.get('user', false)
      if (!!user) {
        global.userToken = user.token
        defaultHeaders['Authorization'] = user.token
      }
    } else {
      defaultHeaders['Authorization'] = global.userToken || ''

    }

    // 'POST' 方法如果传 JSON 格式总返回错误结果
    // if (method === 'POST') {
    //   defaultHeaders['Content-Type'] = 'application/x-www-form-urlencoded'
    // }
    const instance = axios.create({
      baseURL: API.API_HOST,
      timeout: 20000,
      headers: defaultHeaders,
    })

    let response
    if (method === 'GET') {
      console.log('responseGet',response)
      let tUrl=`${'/v2'+url}${data ? `?${qs.stringify(data)}` : ''}`
      console.log('tUrl',tUrl)
      response = await instance.get(tUrl)
      console.log('response',response)
    } else if (method === 'POST') {
      response = await instance.post('/v2'+url, qs.stringify(data))
    } else if (method === 'PATCH') {
      response = await instance.patch('/v2'+url, data)
    } else if (method === 'PUT') {
      response = await instance.put('/v2'+url, data)
    }
    console.log('response',response)
    if (response.data && (response.data.state === 22 || response.data.state === 33)) {
      await Storage.remove('user')
      global.userToken = ''
      //navigateLogin()  //在验证登陆的时候如果没有token返回登陆页
      return {}
    }

    return response.data
  } catch (err) {
    console.log('request error:', err)
    if (err.response && err.response.data && (err.response.data.state === 22 || err.response.data.state === 33)) {
      //await Storage.remove('user')
      global.userToken = ''
      //navigateLogin()
      return {}
    }
    if (err.response && err.response.status === 400) {
      return err.response.data
    }
    // 请求超时
    // if (err.request && err.request.readyState === 4 && err.request.status === 0) {
    //   Toast.show('error', LANG['网络连接失败'] || '网络连接失败', 2000)
    // }
    return {}
  }
}


